#ifndef SENSORTRAYINPUTELEVATOR_H
#define SENSORTRAYINPUTELEVATOR_H

#include "AxisModule/singleaxis.h"
#include "CompositeElement/sccylinder.h"
#include "MotionManager/distatemonitor.h"
#include "Tray/magtraystate.h"
#include "indexvalidator.h"
#include "namedefinition.h"
#include "sensortrayelevatorconfig.h"
#include "systemCore/worker.h"
#include <QMutex>
#include <QMutexLocker>

class SensorTrayInputElevator : public Worker
{
    Q_OBJECT
public:
    explicit SensorTrayInputElevator(SensorTrayElevatorConfig *steConfig, QObject *parent = nullptr);

    // Worker interface
protected:
    virtual void initEventHandle() override;
    virtual void startEventHandle(const WorkerEvent &event) override;
    virtual void stopEventHandle() override;
    virtual void allWorkerStopped() override {}
    virtual void purgeEventHandle() override;
    virtual void resetEventHandle() override;
    virtual void homeWorker(bool moveToReadyPosAfterHome) override;

    // 自动运行逻辑
public slots:
    void moveToNextInitTrayPos();
    void kickTray();
    void retractKicker();
    void setCurrentMagTrayState(MagTrayState::State state);

    // 手动调试操作
public slots:
    void moveToMagTrayPos(int magIndex, int trayIndex);
    void resetMagTrayState(int magIndex);

private slots:
    void onDiStateChanged(QString diName, bool state);
    void onMagTrayCountChanged(int magTrayCount);

private:
    bool hasInitTray(MagTrayState *magTrayState);
    void moveToMagTrayPosImpl(int magIndex, int trayIndex);

private:
    SCDI *stieMagSNR1;
    SCDI *stieMagSNR2;
    SCCylinder *stieCylinder;
    SCCylinder *stieKicker;
    SingleAxis *stie;

    bool isStopping = false;
    QMutex locker;

    MagTrayState *mag1TrayState;
    MagTrayState *mag2TrayState;
    ConfigFile *mag1TrayStateStoreFile;
    ConfigFile *mag2TrayStateStoreFile;
    SensorTrayElevatorConfig *steConfig;

    int currentTrayIndex = -1;

    qint64 magSNR1TurnToOffTimeStamp = 0;
    qint64 magSNR1TurnToOnTimeStamp = 0;
    qint64 magSNR2TurnToOffTimeStamp = 0;
    qint64 magSNR2TurnToOnTimeStamp = 0;
};

#endif    // SENSORTRAYINPUTELEVATOR_H
